<?php
namespace jy_alipay;
defined('BY_JYA') or exit('error');
require_once ROOT_PLUGIN.'jy_alipay/alipay/AopSdk.php';
class alipay extends \plugin{
	public function __construct($setting=array()){
		parent::__construct('jy_alipay');
		if((!$setting || !is_array($setting) || !$setting['alipay_appid']) && $_SESSION['this']=='custom'){
			$setting=uni_setting('pay');
		}elseif(!$setting['alipay_appid']){
			$setting=core_setting('pay');
		}
		if(!$setting['alipay_appid'] || !$setting['alipay_private_key'] || !$setting['alipay_public_key']){
			exi('支付宝的appid，私钥，公钥都必须填写','error');
		}
		$aop = new \AopClient ();
		$aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
		$aop->appId = $setting['alipay_appid'];
		$aop->rsaPrivateKey = $setting['alipay_private_key'];
		$aop->alipayrsaPublicKey=$setting['alipay_public_key']?:'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsjUMEvM/U6Tj2p4ofJFzyx2jdA+o5VYHIRKjozPAw3uCgvaPZEsldcin9pa1doeB4ZdkJ+NFjewUCB53LNieXAmhV1iO8//5O63PmnPrdO1QC82NRUrosUdiMqX5ZVgeG3g96spl31kr46HUr2SnPD2Z+d5tuoMjA6U9yw4fgQAGlcOZMzVnzBS+e56NB81PKh5ViyQIeOt7qXdeaQPlJZFwsAz1E1MbglSXwfaihoYGnTXbz8w+7ZoiThVuae4+UMGQanyQ6qGClsEO+nGGVjrpUN/H0wMxzc0wjKVVlBXbBR6MS6JSEpzm9kmEl2qaq7S8mjfQ62j58qQQ/0IZ4wIDAQAB';
		$aop->apiVersion = '1.0';
		$aop->signType = 'RSA2';
		$aop->postCharset='utf-8';
		$aop->format='json';
		$aop->notify_url=SITEROOT.$_SESSION['this'].'/payresult/alipay_notify.php';
		$this->aop=$aop;
		
	}
	public function request($request,$access_token=null){
		if($access_token){
			$result = $this->aop->execute($request,$access_token); 
		}else{
			$result = $this->aop->execute($request); 
		}
		$responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
		$res =(array)$result->$responseNode;
		if(empty($res)){
			exi('错误代码：参数错误！','error');
		}
		if(!empty($res['code']) && $res['code'] != 10000){
			exi("请求支付宝接口出错！错误码：{$res['code']}，错误内容：{$res['msg']}！",'error');
		} else{
			return $res;
		}
	}
	/*
		支付宝小程序支付，返回支付宝交易单号，用于小程序端发起支付
	*/
	public function aliapp_pay($params){
		$request = new \AlipayTradeCreateRequest();
		$request->setNotifyUrl($this->aop->notify_url);
		$content=array(
			'out_trade_no'=>$params['ordersn'],
			//'seller_id'=>$setting['seller_id'],//卖家支付宝用户ID，可选
			'total_amount'=>$params['fee'],
			'subject'=>$params['title']?:'购买商品',//订单标题
			//'body'=>$params['body'],//对交易或商品的描述
			'buyer_id'=>$params['buyer_id']?:$_SESSION['openid'],//买家的支付宝唯一用户号（2088开头的16位纯数字）
		);
		$content=ijson_encode($content);
		$request->setBizContent($content);
		$result = $this->request($request);
		return $result['trade_no'];
	}
	/*
		小程序获取用户信息。返回用户信息数组
	*/
	public function aliapp_oauth($code,$RefreshToken=''){
		$request = new \AlipaySystemOauthTokenRequest ();
		$request->setGrantType("authorization_code");
		$request->setCode($code);
		if($RefreshToken){
			$request->setRefreshToken($RefreshToken);
		}
		$result = $this->request($request); 
		if($result['user_id']){
			$_SESSION['openid']=$result['user_id'];
			//$access_token=$result['access_token'];
			//$request = new \AlipayUserInfoShareRequest ();
			//$res = $this->request($request,$access_token);
		}
		return $result;
	}
	//异步通知验签，传入收到的请求参数，一般为 $_POST 。返回 bool值 true 或者 false
	public function check_sign($data){
		return $this->aop->rsaCheckV1($data,$this->aop->alipayrsaPublicKey,'RSA2');
	}
	/*
		手机网页支付，返回html
	*/
	public function mobile_pay($params){
		$request = new \AlipayTradeWapPayRequest();
		$request->setReturnUrl($params['return_url']);
		$request->setNotifyUrl($this->aop->notify_url);
		$content=array(
			'out_trade_no'=>$params['ordersn'],
			'total_amount'=>$params['fee'],
			'subject'=>$params['title']?:'购买商品',//订单标题
			//'body'=>$params['body'],//对交易或商品的描述
			'timeout_express'=>'90m',
			'product_code'=>'QUICK_WAP_WAY',
		);
		$content=ijson_encode($content);
		$request->setBizContent($content);
		$result = $this->aop->pageExecute ($request); 
		return $result;
	}
	/*
		电脑网页支付，返回html
	*/
	public function pc_pay($params){
		$request = new \AlipayTradePagePayRequest ();  
		$request->setReturnUrl($params['return_url']);
		$request->setNotifyUrl($this->aop->notify_url);
		$content=array(
			'out_trade_no'=>$params['ordersn'],
			'total_amount'=>$params['fee'],
			'subject'=>$params['title']?:'购买商品',//订单标题
			//'body'=>$params['body'],//对交易或商品的描述
			'product_code'=>'FAST_INSTANT_TRADE_PAY',
		);
		$content=ijson_encode($content);
		$request->setBizContent($content);  
		$result = $this->aop->pageExecute($request);
		return $result;
	}
	/*
		APP支付，返回app端可用的参数集
	*/
	public function app_pay($params){
		$request = new \AlipayTradeAppPayRequest();
		$content=array(
			'out_trade_no'=>$params['ordersn'],
			'total_amount'=>$params['fee'],
			'subject'=>$params['title']?:'购买商品',//订单标题
			//'body'=>$params['body'],//对交易或商品的描述
			'product_code'=>'QUICK_MSECURITY_PAY',
			'timeout_express'=>'30m',
		);
		$content=ijson_encode($content);
		$request->setBizContent($content);  
		$request->setNotifyUrl($this->aop->notify_url);
		//这里和普通的接口调用不同，使用的是sdkExecute
		$result = $this->aop->sdkExecute($request);
		return $result;
	}
	
}